const APIQuery = require('./api/Query');
const redisClient = require('../redis/redisClient');
const logger = require('../utils').getLogger(__filename);
const { EventEmitter } = require('eventemitter3');
const errors = require('./error');
const config = require('config');
const { sleep } = require("../utils");
const cruiseTimeout = config.get('agora.cruiseTimeout')

class IntervalQuery extends EventEmitter {
	constructor(props) {
		super();
		// this.queueInterval = setInterval(this.cruise.bind(this), cruiseTimeout)
		this.cruise()
	}

	async cruise() {
		try {
			let records = await redisClient.getAllRecords();
			logger.info(`开始轮询录制记录：${records.length}`)
			for (let i = 0; i < records.length; i++) {
				let key = records[i];
				let info = await redisClient.getMeetingInfo(key);

				if (!info) {
					// redisClient.deleteMeetingInfo(key);
					// this.emit('delete', key)
					continue;
				}

				let query = new APIQuery({ resourceId: info.resourceId, sid: info.sid }, info.modal);
				await query.run().then(ret => {
					this.emit(`info`, ret, info, key)
					this.emit(`info ${info.meetingId}`, ret, info, key)
				}).catch(e => {
					// if (e instanceof errors.Error400 || e instanceof errors.Error404) {
						// redisClient.deleteMeetingInfo(key);
					// }
					this.emit('error', e, info, key)
				})
			}
		} catch (e) {
			logger.error('IntervalQuery run error:')
			logger.error(e)
		}
		await sleep(cruiseTimeout)
		this.cruise()
	}
}

module.exports = new IntervalQuery()

